# !/usr/bin/env python
# -*- coding:utf-8 -*-
# @FileName : zsj.py
# @Time     : 2024/4/9 19:22
# @Author   : Robot-Zsj
"""
description:

input
3
3
1 2 3 0
1 3 1 0
2 3 5 0
output
4
"""
import sys

n = int(input())
m = int(input())

graph = [[sys.maxsize for _ in range(n + 1)] for _ in range(n + 1)]

for _ in range(m):
    x, y, z, p = map(int, input().split())

    if p == 0:
        graph[x][y] = z
        graph[y][x] = z
    else:
        graph[x][y] = 0
        graph[y][x] = 0


def prim():
    minWeight = 0

    inTree = [False] * (n + 1)

    inTree[1] = True

    inTree_count = 1

    dis = [0] * (n + 1)
    for i in range(1, n + 1):
        dis[i] = graph[1][i]

    while inTree_count < n:
        minDis = sys.maxsize
        nodeIdx = 0

        for i in range(1, n + 1):
            if not inTree[i] and dis[i] < minDis:
                minDis = dis[i]
                nodeIdx = i

        if nodeIdx == 0:
            return -1

        inTree[nodeIdx] = True
        inTree_count += 1
        minWeight += dis[nodeIdx]

        for i in range(1, n + 1):
            if not inTree[i] and graph[nodeIdx][i] < dis[i]:
                dis[i] = graph[nodeIdx][i]

    return minWeight


print(prim())
